﻿Shader "Unlit/DiffuseWithShadow"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType" = "Opaque"}
        LOD 100

        Pass
        {
            Tags {"LightMode" = "ForwardBase"}
            CGPROGRAM
            // enable renderdoc debug
            #pragma enable_d3d11_debug_symbols
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"
            #include "Lighting.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
                fixed4 color : COLOR;
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
                float3 normal : NORMAL;//world normal
                fixed4 color : COLOR;
                float4 lightPosition : TEXCOORD0;
            };

            float4x4 lightVP;
            sampler2D shadowMap;

            v2f vert(appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.normal = normalize(mul((float3x3)unity_ObjectToWorld, v.normal));
                o.color = v.color;
                o.lightPosition = mul(lightVP, mul(unity_ObjectToWorld, v.vertex));
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                fixed3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
                fixed3 diffuse = _LightColor0.rgb * i.color.rgb * saturate(dot(i.normal, worldLight));
                fixed3 color = diffuse + ambient;

                float depth = i.lightPosition.z / i.lightPosition.w;
                fixed4 depthColor = tex2D(shadowMap, float2(i.lightPosition.x / i.lightPosition.w, i.lightPosition.y / i.lightPosition.w));
                float d = DecodeFloatRGBA(depthColor);
                float shadowScale = step(d, depth);
                shadowScale = shadowScale / 2 + 0.5;
                return float4(color * shadowScale, 0);
            }
            ENDCG
        }
    }
}
